package com.gexin.controller.xapp;

import com.gexin.common.app.JpushMsgType;
import com.gexin.common.app.JpushTools;
import com.gexin.common.cache.CacheUtils;
import com.gexin.common.model.ApiResponse;
import com.gexin.common.utils.MessageUtils;
import com.gexin.common.utils.StringUtil;
import com.gexin.controller.system.LoginController;
import com.gexin.core.web.AppController;
import com.gexin.model.activity.MemberInfo;
import com.gexin.model.weixin.WeixinUser;
import com.gexin.service.memberAcitivty.InviterService;
 import com.jfinal.core.NotAction;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.log.Log;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 微信-手机号码登录到APP
 *
 * @author 肖得明
 */
@ControllerBind(controllerKey = "/xapp/app/login")
public class AppLoginController extends AppController {
	static Log log = Log.getLog(LoginController.class);

	//测试APP登录
	public void testToken() {
		WeixinUser user = WeixinUser.dao.findById("109799");
		renderJson(login_event(user));
	}



	public void weixin() {
		String unionid = getPara("unionid");
		String openid = getPara("openid");
		String headimgurl = getPara("headimgurl");
		String nickname = getPara("nickname");
		String province = getPara("province");
		String city = getPara("city");
		if (StringUtil.isBlank(unionid) || StringUtil.isBlank(openid)) {
			fail("请检参数是否正确");
			return;
		}
		WeixinUser user = WeixinUser.dao.getUserByUnionid(unionid);
		ApiResponse response = null;
		if (user != null) {
			// && user.getUserType()==Wxuser.UserType_Weixin
			if (StringUtil.isBlank(user.getAppOpenid())) {
				user.setAppOpenid(openid);
				user.update();
			}
			response = login_event(user);
		} else {
			user = new WeixinUser();
			user.setCity(city);
			user.setProvince(province);
			user.setHeadimgurl(headimgurl);
			user.setNickname(nickname);
			user.setAppOpenid(openid);
			user.setUnionid(unionid);
			user.save();
			response = login_event(user);
		}
		renderJson(response);
	}

	// 登录的业务逻辑代码
	@NotAction
	private ApiResponse login_event(WeixinUser user) {
		String jpushid = getPara("jpushid");
		if (StringUtil.isBlank(jpushid)) {
			log.info("用户ID：" + user.getId() + "，获取JpushId为空！");
		}
		String yljpushid = WeixinUser.dao.cache_getJpulishId(user.getId());
		if (StringUtil.show(yljpushid).equals("offline") || StringUtil.isBlank(yljpushid)) {
			WeixinUser.dao.cache_setJpulishId(user.getId(), jpushid);
		} else if (StringUtil.isNotBlank(jpushid)) {
			// 原来的yljpushid为空时
			if (StringUtil.isBlank(yljpushid)) {
				WeixinUser.dao.cache_setJpulishId(user.getId(), jpushid);
			} else if (!StringUtil.show(yljpushid).equals(jpushid)) {
				// 表示其他的设备登录了
				log.info("不等于：" + jpushid + "========原来的：" + yljpushid);
				WeixinUser.dao.cache_setJpulishId(user.getId(), jpushid);
				JpushTools.SendMessageToAppNeibu(true, "您的账户在其他的地方登录了！", yljpushid, JpushMsgType.Type_Logout, null);
			}
		}
		if (StringUtil.isNotBlank(user.getLoginToken())) {
			// 如果不是空的 要删除以前的token
			CacheUtils.del(WeixinUser.cache_User_TokenGetUserfd + user.getLoginToken());
		}
		user.setLoginToken(StringUtil.generID());// 生成新的token
		CacheUtils.set(WeixinUser.cache_User_TokenGetUserfd + user.getLoginToken(), user.getId());
		// 设置最后登录时间
		user.update();
		// 还要判断设备重复登录
		user = WeixinUser.dao.findById(user.getId());
		ApiResponse response = new ApiResponse(user);
		if (StringUtil.isBlank(user.getMobile())) {
			response.setState(false);
			response.setCode(1004);
		}
		return response;
	}


	/**
	 * 退出
	 */
	public void logout() {
		String token = getRequest().getParameter("token");
		Integer user_id = WeixinUser.dao.isActiveToken(token);
		if (user_id == null) {
			fail("token 无效！");
			return;
		}
		CacheUtils.del(WeixinUser.cache_User_TokenGetUserfd + token);
		WeixinUser.dao.cache_setJpulishId(user_id, "offline");
		success();
	}


	//小金鱼挪过来的代码

	//发送验证码
	public void sendVerificationCode() {
		String phone = getPara("phone");
		if (StringUtils.isEmpty(phone)) {
			fail("请输入手机号！");
			return;
		}
		Random rand = new Random();
		String code = StringUtil.fillString(rand.nextInt(10000) + "", "0", 4, StringUtil.FILL_TYPE_LEFT);
		renderJson(MessageUtils.SendCode_New(phone, code, MessageUtils.loginId,getRequest()));
	}

	//手机号登录
	public void phone() {
		String inviteCode = getPara("inviteCode");
		String phone = getPara("phone");
		String code = getPara("code");
		if (StringUtils.isNotBlank(inviteCode)) {
			InviterService inviterService = new InviterService();
			ApiResponse apiResponse = inviterService.getInviterCode(inviteCode);
			if (apiResponse.isState() == false) {
				fail(apiResponse.getMsg());
				return;
			}
		}
		if (StringUtil.isBlank(phone)) {
			fail("请输入手机号！");
			return;
		}

		if (StringUtil.isBlank(code)) {
			fail("请输入验证码！");
			return;
		}

		if (!MessageUtils.CheckCode(phone, code, MessageUtils.loginId)) {
			fail("验证码错误！");
			return;
		}

		WeixinUser user = WeixinUser.dao.findbyBindPhone(phone);
		if (user == null) {
			user = new WeixinUser();
			user.setHeadimgurl("http://img.weizhi.so/head2.jpg");
			user.setBindPhone(phone);
			user.setMobile(phone);
			user.setNickname("中科易购_" + phone);
			user.save();
			String id = user.getId() + "";
			MemberInfo memberInfo = new MemberInfo();
			memberInfo.setMemberInfo(System.currentTimeMillis() / 1000 + "", id + "", 0, phone);
			if (inviteCode != null) {
				memberInfo.setMemberInfo(System.currentTimeMillis() / 1000 + "", id + "", 0, phone);
				memberInfo.save();
				if (StringUtils.isNotBlank(inviteCode)) {
					InviterService inviterService = new InviterService();
					ApiResponse apiResponse = inviterService.inviter(id, inviteCode);
					if (apiResponse.isState() == false) {
						fail(apiResponse.getMsg());
						return;
					}
				}

				renderJson(login_event(user));
 			} else {
				renderJson(login_event(user));
 			}
		} else {
			renderJson(login_event(user));
 		}
	}
	/**
	 * 是否开启手机号登录
	 */
	public void  isOpenPhoneLogin(){
		Map<String,Object> dataMap=new HashMap<>();
		dataMap.put("isOpenPhoneLogin",true);//是否开启手机号登录
		dataMap.put("isOpenWeChatLogin",false);//是否开启微信登录
		dataMap.put("is_pre_sale_products",false);//是否显示敬请期待
		dataMap.put("isCancelAccount",true);//是否显示注销账号入口
		success(dataMap);
	}


	/**
	 * 绑定手机号
	 */
	public void bindPhone(){
		String phone=getPara("phone");
		String code=getPara("code");

		if (StringUtil.isBlank(phone)){
			fail("请输入手机号！");
			return;
		}

		if (StringUtil.isBlank(code)){
			fail("请输入验证码！");
			return;
		}

		if (!MessageUtils.CheckCode(phone, code,MessageUtils.loginId)){
			fail("验证码错误！");
			return;
		}
		WeixinUser user=getAuthUser();
		user.setBindPhone(phone);
		user.update();
		success("绑定成功！");
	}

}
